<template>
  <div class="form-fragment">
    <div class="form-container">
      <tbc-dynamic-form :form="dynamicForm" class="compact"/>

      <el-form label-width="80px" label-position="top" style="max-width: 80%">
        <div class="sku-container">

          <div class="clearfix" :key="index" v-for="(attr, index) in attributeList" style="margin-bottom: 20px">
            <el-form-item :label="attr.attr_name" :key="index">
              <el-checkbox-group v-model="attr.checked">
                <el-checkbox
                    :label="item.value"
                    :key="item.value"
                    v-for="item in attr.attr_values" @change="onPresetCheckboxChange(attr, item)">
                  <span>{{ item.label }}</span>
                  <input
                      type="text"
                      class="attr__notes"
                      placeholder="备注"
                      v-if="attr.checked.indexOf(item.value) > -1"
                      v-model="item.remark"
                      @keyup="renderTableView">
                </el-checkbox>
              </el-checkbox-group>
              <el-checkbox-group v-model="attr.checked">
                <el-checkbox
                    :label="item.value"
                    :key="item.value"
                    :checked="item.checked"
                    v-for="(item, idx) in attr.custom_values"
                    @change="onCustomCheckboxChange(attr, item, idx)">
                  <input
                      type="text"
                      class="attr__notes"
                      placeholder="其他"
                      v-model="item.label"
                      @keyup.stop="onCustomInputKeyUp(attr, item, idx)">
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>

          </div>
        </div>

        <el-form-item>
          <template v-slot:label>
            <div>
              <label class="el-form-item__label">销售属性</label>
              <div class="fill">
                <el-input v-model="fillForm.skuPrice" placeholder="价格" size="small"></el-input>
                <el-input v-model="fillForm.skuStock" placeholder="库存" size="small"></el-input>
                <el-input v-model="fillForm.skuOuterId" placeholder="商家编码" size="small"></el-input>
                <el-input v-model="fillForm.skuBarcode" placeholder="商品码" size="small"></el-input>
                <el-button size="small" type="primary" @click="fillValue(true)">填充</el-button>
              </div>
            </div>

          </template>
          <div class="sku-table" ref="skuContainer">

          </div>
        </el-form-item>
      </el-form>
    </div>
    <tbc-file-manager ref="file" @select="onFileSelect" :selectable="['image']" :max="1"/>
  </div>
</template>
<script lang="ts">
import {defineComponent, reactive, Ref, ref, toRefs} from 'vue'

interface Attribute {
  uuid?: string
  attr_id: string
  value: string,
  label: string,
  remark: string,
  attr_values?: { value: string, label: string }[],
  custom_values?: Attribute[],
  checked?: string[]
}

interface Option {
  uuid?: string,
  attr_id: string,
  value: string | number,
  label: string,
  remark?: string
}

export default defineComponent({

  name: 'goods-form-spec',

  setup() {

    let skuUploadCallback: any = null
    const file: Ref = ref(null)
    const skuInstance = new (window as any).skuBuilder({
      isMergeCell: true,
      onUploadClick: function (callback: any) {
        skuUploadCallback = callback
        file.value.show()
        // setTimeout(() => {
        //   skuUploadCallback('https://fuss10.elemecdn.com/9/bb/e27858e973f5d7d3904835f46abbdjpeg.jpeg');
        // }, 1000)
      }
    });

    const onFileSelect = (files: { file_url: string }[]) => {
      if (!files.length) return
      if (skuUploadCallback) skuUploadCallback(files[0].file_url)
    }


    const state = reactive({
      dynamicForm: [
        {label: '市场价', type: 'input-number', field: 'market_price', value: 0, remark: ''},
        {label: '销售价', type: 'input-number', field: 'shop_price', value: 0, remark: '(如果添加多规格则无效)'},
        {label: '库存', type: 'input-number', field: 'stock', value: 0, remark: '(如果添加多规格则无效)'},
      ],
      skuTableHtml: '',
      skuBatchHtml: '',
      attributeList: [], skuAttribute: [], initFormData: [],
      fillForm: {skuPrice: '', skuStock: '', skuOuterId: '', skuBarcode: ''},
      index: -1,
      cols: [],
      skuFormData: [],
      skuUploadItem: null
    })
    const skuContainer: Ref = ref(null)
    const init = (data) => {
      if (data === undefined) return
      state.dynamicForm.forEach(item => {
        if (data[item.field] !== undefined) item.value = Number(data[item.field])
      })
      state.skuFormData = data.goods_spec || []
      skuInstance.setFormData(state.skuFormData)
      detectSelected()
    }


    // 设置规格属性列表
    const setAttributeList = (attrList: Attribute[]): void => {
      attrList.forEach((item: Attribute) => {
        if (item.custom_values === undefined) item.custom_values = []
        item.custom_values.push(buildCustomItem(item))
        item.checked = []
      })
      state.attributeList = attrList as any;
      detectSelected()
    }

    // 生成自定义选择框
    const buildCustomItem = (attr: { attr_id: string }) => {
      return {
        uuid: skuInstance.uuid(),
        attr_id: attr.attr_id,
        value: 'CUSTOM_' + new Date().valueOf(), label: '', remark: ''
      }
    }

    // 预设值复选框改变
    const onPresetCheckboxChange = () => {
      renderTableView()
    }

    // 自定义选框改变
    const onCustomCheckboxChange = (attr: { [k: string]: any, attr_id: string }, item: Option, index: number) => {
      if (attr.checked.indexOf(item.value) > -1) {
        attr.custom_values.push(buildCustomItem(attr));
      } else {
        attr.custom_values.splice(index, 1)
      }
      renderTableView()
    }


    // 自定义内容输入
    const onCustomInputKeyUp = (attr: { [k: string]: any, attr_id: string }, item: Option) => {
      attr.checked.indexOf(item.value) > -1 && renderTableView()
    }
    // 渲染表格
    const renderTableView = () => {
      const cols: { label: string, prop: string }[] = []
      const attr: { id: string, name: string, node: Option[] }[] = []

      state.attributeList.forEach((item: any, index: number) => {
        const checked: Option[] = [];
        item.checked.forEach((value: string | number) => {
          item.attr_values.forEach((option: Option) => {
            if (option.value === value) checked.push(option);
          });
          item.custom_values.forEach((option: Option) => {
            if (option.value === value) checked.push(option);
          });
        });

        if (checked.length) {
          attr.push({id: item.attr_id, name: item.attr_name, node: checked});
          cols.push({label: item.attr_name, prop: 'key:' + index})
        }
      });
      let skuFormData = skuInstance.getFormData()
      if (skuFormData.length) state.skuFormData = skuFormData
      skuContainer.value.innerHTML = ''
      if (!cols.length) return
      skuContainer.value.append(skuInstance.setAttrList(attr).build())
      skuInstance.setFormData(state.skuFormData)
    }

    // 填充
    const fillValue = () => {
      for (let i in state.fillForm) {
        if (state.fillForm[i]) skuInstance.fill(i, state.fillForm[i])
      }
    }

    // 检测选中的值
    const detectSelected = () => {
      if (!state.attributeList.length || !state.skuFormData.length) return
      const props: Record<string, { [k: string]: string | number }> = {} // 获取已选中的属性值
      state.skuFormData.forEach((data: { props: Record<string, string>[] }) => {
        data.props.forEach((prop: Record<string, string>) => {
          const key: string = [prop.attr_id, prop.value].join('_')
          props[key] = prop
        })
      })


      state.attributeList.forEach((attr: Record<string, any>) => {
        for (let i in props) {
          const prop = props[i]
          if (attr.attr_id === prop.attr_id) {
            attr.checked.push(prop.value)
            let isCustom = true
            attr.attr_values.forEach(item => {
              if (item.value === prop.value) {
                item.remark = prop.remark
                isCustom = false
              }
            });
            if (isCustom) attr.custom_values.unshift(prop)
          }
        }
      })
      renderTableView();
    }

    const getFormData = () => {
      const form: Record<string, any> = {}
      state.dynamicForm.forEach(item => form[item.field] = item.value)
      let skuData = skuInstance.getFormData()
      console.log(skuData)

      skuData.forEach((item: Record<string, any>) => {
        item.props.forEach((prop: Record<string, any>) => {
          let value = prop.value
          if (typeof value === 'string' && prop.value.indexOf('CUSTOM_') > -1) {
            prop.value = prop.label
          }
        })
      })
      console.log(skuData)
      form.goods_spec = JSON.stringify(skuData)
      return form
    }
    return {
      ...toRefs(state),
      file,
      init,
      fillValue,
      getFormData,
      skuContainer,
      setAttributeList,
      onPresetCheckboxChange,
      onCustomCheckboxChange,
      onCustomInputKeyUp,
      renderTableView,
      onFileSelect
    }
  }
})
</script>
<style>
.category-box {
  width: 100%;
  border: 1px solid #dcdfe6;
  min-height: 500px;
}

.attr__notes {
  width: 80px;
  line-height: 20px;
  padding: 0 4px;
  border: 1px solid #dcdfe6;
  margin-left: 4px;
}

.sku-container .el-form-item__content {
  line-height: 32px;
}

.sku-container .el-checkbox {
  float: left;
  margin-left: 0;
  margin-right: 30px;
  min-width: 200px;
}

.sku-container .el-checkbox__label {
  padding-left: 4px;
}

.sku-layout-table {
  width: 100%;
  background: #fff;
  border-collapse: collapse;
  margin: 10px 0 0;
}

.sku-layout-table thead tr {
  background: #f5f7fa;
}

.sku-layout-table th, .sku-layout-table td {
  padding: .625em 1em;
  line-height: 1em;
  border: 1px solid #ebeef5;
  font-size: 1em;
}

.sku-layout-table th {
  text-align: left;
  font-weight: normal;
}

.sku-layout-table tr {
  transition: all .2s;
  -webkit-transition: all .2s;
}

.sku-layout-table input, .sku-layout-table input:focus {
  border: none;
  outline: 0;
  background: none;
  width: 100%;
}

.sku-layout-table th, .sku-layout-table input {
  height: 24px;
  line-height: 24px
}

.sku-batch input {
  height: 24px;
  line-height: 24px;
  border: 1px solid #dcdfe6;
  margin-right: 10px;
  padding: 0 10px;
  width: 80px;
}

.fill .el-input {
  width: 100px;
  margin-right: 10px
}
</style>
